package com.kaifamiao.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@Configuration
@ComponentScan("com.kaifamiao.service")
@PropertySource("classpath:db.properties")
public class ApplicationConfig {

    @Bean("dataSource")
    public DataSource createDateSource(@Value("${jdbc.driver}") String driver,
                                       @Value("${jdbc.url}")String url,
                                       @Value("${jdbc.username}")String useranme,
                                       @Value("${jdbc.password}")String password){
        ComboPooledDataSource dataSource= new ComboPooledDataSource();
        try {
            dataSource.setDriverClass(driver);
            dataSource.setJdbcUrl(url);
            dataSource.setUser(useranme);
            dataSource.setPassword(password);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean createFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.kaifamiao.model");
        return factoryBean;
    }

    @Bean
    public MapperScannerConfigurer createScannerConfigure(){
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage("com.kaifamiao.mapper");
        return configurer;
    }

}
